package code;
import models.ListNode;
public class FindKthToTail {
    public ListNode Solution(ListNode head,int k) {
        if(head==null){
            return null;
        }
        int count = 1;
        ListNode q = head;
        while(q.next!=null){
            count++;
            q = q.next;
        }
        if(count<k){
            return null;
        }
        ListNode p = head;
        for(int i=0;i<count-k;i++){
            p = p.next;
        }
        return p;

    }

    public static void main(String[] argv){
        FindKthToTail findKthToTail = new FindKthToTail();
        int[] a = new int[]{1,2,3,4,5};
        ListNode head = new ListNode(a[0]);
        ListNode p = head;
        for(int i=1;i<a.length;i++){
            p.next= new ListNode(a[i]);
            p = p.next;
        }
        ListNode re = findKthToTail.Solution(null,5);
        for(int i=0;i<5;i++){
            System.out.println(re.val);
            re = re.next;
        }
    }


}
